<template>
  <div class="base-container">
    <el-form
      ref="toolQuery"
      :model="toolQuery"
      :rules="toolQueryRules"
      size="small"
      label-width="65px"
      v-show="toolQueryVisiable"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="toolQuery.username"
              placeholder="请输入用户名"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="toolQuery.nickname"
              placeholder="请输入昵称"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="toolQuery.status" size="mini">
              <el-radio-button
                v-for="(item, index) in statusOptions"
                :key="index"
                :label="item.value"
                :disabled="item.disabled"
                >{{ item.label }}</el-radio-button
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="initData" size="mini"
            >提交</el-button
          >
          <el-button @click="resetForm" size="mini">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
    <toolBar
      :tableColumnConfig="tableColumnConfig"
      :checkedRow="checkedRow"
      :dataList="dataList"
      :toolBarAddBTN="toolBarAddBTN"
      @add="openAdd"
      @edit="edit"
      @del="del"
    ></toolBar>
    <el-table :data="dataList" border>
      <template v-for="item in cptColumn">
        <el-table-column
          :label="item.label"
          :prop="item.prop"
          v-if="!excludeHandle(item.prop)"
          :key="item.id"
        ></el-table-column>
        <el-table-column
          v-if="item.prop == 'sex'"
          :key="item.id"
          :label="item.label"
        >
          <template slot-scope="scope">
            {{ radioName(scope.row["sex"], sexOptions) }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="item.prop == 'status'"
          :key="item.id"
          :label="item.label"
        >
          <template slot-scope="scope">
            {{ radioName(scope.row["status"], statusOptions) }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="item.prop == 'avatar'"
          :key="item.id"
          :label="item.label"
        >
          <template slot-scope="scope">
            <!-- <img :src="scope.row['avatar']" alt="" style="width: 50px;height: 50px"> -->
            <el-image
              :src="staticBaseSrc + scope.row['avatar']"
              :preview-src-list="[staticBaseSrc + scope.row['avatar']]"
              fit="contain"
              style="width: 35px;height: 35px"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="openEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="del(scope.row)"
            >删除</el-button
          >
          <el-button type="text" size="small" @click="resetPa(scope.row)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="query.page"
      :page-sizes="[5, 10, 20, 400]"
      :page-size="query.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="query.totalRow"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <detail
      :roleUidOptions="roleUidOptions"
      :dialogVisible="dialogVisible"
      ref="detail"
      @addHandle="add"
      @editHandle="edit"
    ></detail>
  </div>
</template>

<script>
/*
  通用表格使用说明
    配套功能 ---
      1.工具栏 --- 配置列、增、删、改、查
      2.表格自动渲染列
      3.分页栏
    使用步骤
      1.引入 CURD类
      2.引入需要的组件

    需要注意的配置列时候 id必须从1开始
    遍历列的时候需要使用 计算属性  --- cptColumn
*/
import toolBar from "@/components/common/toolBar";
import curd from "@/mixins/curd";
import detail from "./component/detail";
import { sendJSON } from "@/utils/request";
import { mapGetters } from "vuex";
const CURD = new curd({
  url: "/sys/user/"
});
export default {
  components: { toolBar, detail },
  mixins: [CURD],
  data() {
    return {
      tableColumnConfig: [
        { id: 1, label: "账号", prop: "username", show: true },
        { id: 2, label: "用户名", prop: "nickname", show: true },
        { id: 3, label: "头像", prop: "avatar", show: true },
        { id: 4, label: "角色", prop: "roleName", show: true },
        { id: 5, label: "性别", prop: "sex", show: true },
        { id: 6, label: "状态", prop: "status", show: true },
        { id: 7, label: "电话", prop: "phoneNumber", show: true },
        { id: 8, label: "邮箱", prop: "email", show: true },
        { id: 9, label: "创建时间", prop: "created", show: true },
        { id: 10, label: "更新时间", prop: "updated", show: true }
      ],
      // 详情 -- 角色数组
      roleUidOptions: [],
      // 不渲染的列
      exclude: ["avatar", "status", "sex"],
      toolQuery: {
        username: undefined,
        nickname: undefined,
        status: undefined
      },
      toolQueryRules: {
        username: [],
        nickname: [],
        status: []
      },
      statusOptions: [
        {
          label: "未激活",
          value: 1
        },
        {
          label: "禁用",
          value: 2
        },
        {
          label: "启用",
          value: 3
        }
      ],
      sexOptions: [
        {
          label: "男",
          value: 1
        },
        {
          label: "女",
          value: 2
        }
      ]
    };
  },
  methods: {
    // 刷新-API
    initData() {
      this.tableLoading = true;
      let data = JSON.parse(JSON.stringify(this.query)),
        toolQuery = JSON.parse(JSON.stringify(this.toolQuery));
      // page - 页码
      // size - 页目数
      Object.assign(data, toolQuery);
      sendJSON(this.initUrl, data).then(res => {
        console.log(
          "%cMyProject%cline:264%cvar",
          "color:#fff;background:#ee6f57;padding:3px;border-radius:2px",
          "color:#fff;background:#1f3c88;padding:3px;border-radius:2px",
          "color:#fff;background:rgb(251, 178, 23);padding:3px;border-radius:2px",
          res
        );
        this.dataList = res.data.list;
        this.query.totalRow = res.data.totalRow;
        this.tableLoading = false;
      });
      sendJSON("/sys/role/page", { size: 999999999 }).then(res => {
        this.roleUidOptions = res.data.list;
      });
    },
    // 打开编辑弹窗
    openEdit(obj) {
      console.log("重新定义了", obj);
      this.$refs.detail.dialogVisible = true;
      this.$refs.detail.title = "编辑";
      this.$refs.detail.isAdd = false;
      const from = JSON.parse(JSON.stringify(obj));
      let url = this.staticBaseSrc + from.avatar;
      this.$refs.detail.avatarfileList = [
        {
          name: `${Math.random()}`,
          uid: Math.random(),
          url
        }
      ];
      this.$refs.detail.formData = from;
    },
    // 打开添加弹窗
    openAdd() {
      this.$refs.detail.avatarfileList = [];
      this.$refs.detail.dialogVisible = true;
      (this.$refs.detail.title = "添加"), (this.$refs.detail.isAdd = true);
      this.$refs.detail.formData = {
        nickname: undefined,
        email: undefined,
        phoneNumber: undefined,
        sex: false,
        status: false,
        roleUid: undefined,
        remark: undefined,
        avatar: null,
        username: "",
        password: ""
      };
    },
    // 重置密码
    resetPa(obj) {
      this.$confirm("是否确定要重置该账户密码?", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "放弃操作"
      })
        .then(() => {
          let param = { uid: obj.uid };
          sendJSON("/sys/user/resetPsw", param).then(res => {
            this.$message.success(res.msg);
          });
        })
        .catch(() => {
          this.$message("操作已取消~");
        });
    },
    // 重置顶部查询
    resetForm() {
      this.$refs["toolQuery"].resetFields();
    },
    // 单选匹配
    radioName(key, arr) {
      return arr.filter(item => key == item.value)[0].label;
    }
  },
  computed: {
    ...mapGetters(["staticBaseSrc"])
  }
};
</script>

<style lang="scss">
@import "@/styles/base/index.scss";
</style>
